#ifndef __BOLCK_QUEUE_HPP_
#define __BOLCK_QUEUE_HPP_
#include <iostream>
#include <string>
#include <queue>
#include <pthread.h>

using namespace std;

template<class T>
class BlockQueue
{
public:
    BlockQueue(int cap):_cap(cap)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_product_cond,nullptr);
        pthread_cond_init(&_consum_cond,nullptr);
    }

    void Enqueue(const T& in)
    {
        pthread_mutex_lock(&_mutex);
        if(isfull())
        {
            _product_wait_num++;
            pthread_cond_wait(&_product_cond,&_mutex);
            _product_wait_num--;
        }
        _block_queue.push(in);
        pthread_cond_signal(&_consum_cond);
        pthread_mutex_unlock(&_mutex);
    }

    void pop(T *out)
    {
        pthread_mutex_lock(&_mutex);

        if(isempty())
        {
            _consum_wait_num++;
            pthread_cond_wait(&_consum_cond,&_mutex);
            _consum_wait_num--;
        }
        *out = _block_queue.front();
        _block_queue.pop();
        pthread_cond_signal(&_product_cond);
        pthread_mutex_unlock(&_mutex);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_product_cond);
        pthread_cond_destroy(&_consum_cond);
    }

private:
    bool isfull()
    {
        return _block_queue.size() == _cap;
    }

    bool isempty()
    {
        return _block_queue.empty();
    }
private:
    queue<T> _block_queue;
    int _cap;

    pthread_mutex_t _mutex;//保护_block_queue 的锁
    pthread_cond_t _product_cond;//给生产者提供的条件变量
    pthread_cond_t _consum_cond;//给消费者提供的条件变量

    int _product_wait_num = 0;
    int _consum_wait_num = 0;
};



#endif
